package com.training.web.service;

import com.training.web.repository.WebUserRepository;
import com.training.bean.User;
import com.training.utils.MD5Util;
import com.training.utils.FileUploadUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class WebUserService {

    @Autowired
    private WebUserRepository webUserRepository;
    
    @Autowired
    private FileUploadUtil fileUploadUtil;
    
    private final String defaultAvatarPath = "/images/default-avatar.png";

    public List<User> getAllUsers() {
        return webUserRepository.findAll();
    }
    public User searchUsersById(int id) {
        return webUserRepository.findUserById(id);
    }
    public List<User> searchUsersByPhone(String phone) {
        return webUserRepository.findUsersByPhone(phone);
    }
    private final WebUserRepository repository;

    @Autowired
    public WebUserService(WebUserRepository repository) {
        this.repository = repository;
    }

    public User findUser(String phone) {
        return repository.findUserByPhone(phone);
    }

    public List<User> findAllUsers() {
        return repository.findAll();
    }

    public User addUser(User user) throws Exception {
        return addUser(user, null);
    }

    public User addUser(User user, HttpServletRequest request) throws Exception {
        // 检查手机号是否已经存在
        User existingUser = repository.findUserByPhone(user.phone);
        if (existingUser != null) {
            throw new Exception("手机号已经存在");
        }

        // 对密码进行MD5加密
        if (user.password != null && !user.password.isEmpty()) {
            user.password = MD5Util.encrypt(user.password);
        }

        // 如果没有头像，则使用默认头像
        if (user.avatar == null || user.avatar.isEmpty()) {
            user.avatar = defaultAvatarPath;
        }

        // 设置创建和更新时间
        Date currentTime = new Date();
        user.cread_date = currentTime;
        user.updata_date = currentTime;

        // 保存用户
        return repository.save(user);
    }

    public User updateUser(User user) throws Exception {
        return updateUser(user, null);
    }

    public User updateUser(User user, HttpServletRequest request) throws Exception {
        // 检查用户是否存在
        Optional<User> existingUserOpt = repository.findById(user.id);
        if (!existingUserOpt.isPresent()) {
            throw new Exception("用户不存在");
        }

        User existingUser = existingUserOpt.get();

        // 检查手机号是否已被其他用户使用
        User userWithSamePhone = repository.findUserByPhone(user.phone);
        if (userWithSamePhone != null && userWithSamePhone.id != user.id) {
            throw new Exception("手机号已被其他用户使用");
        }


        // 更新用户信息
        existingUser.nickname = user.nickname;
        existingUser.phone = user.phone;
        // 只有当新头像URL不为空时才更新头像
        if (user.avatar != null && !user.avatar.isEmpty()) {
            existingUser.avatar = user.avatar;
        } else if ((existingUser.avatar == null || existingUser.avatar.isEmpty()) && request != null) {
            // 如果当前用户没有头像且更新时也未提供，则使用默认头像（仅在request不为空时）
            existingUser.avatar = defaultAvatarPath;
        }

        // 更新时间
        Date currentTime = new Date();
        existingUser.updata_date = currentTime;

        // 保存用户
        User updatedUser = repository.save(existingUser);
        return updatedUser;
    }

    public boolean deleteUser(int userId) throws Exception {
        // 检查用户是否存在
        Optional<User> user = repository.findById(userId);
        if (!user.isPresent()) {
            throw new Exception("用户不存在");
        }

        // 删除用户头像文件（如果不是默认头像）
        User userToDelete = user.get();
        if (userToDelete.avatar != null && !userToDelete.avatar.isEmpty() && !isDefaultAvatar(userToDelete.avatar)) {
            fileUploadUtil.deleteFile(userToDelete.avatar);
        }

        try {
            repository.deleteById(userId);
            return true;
        } catch (Exception e) {
            throw new Exception("删除用户失败: " + e.getMessage());
        }
    }

    public User toggleUserDisabledStatus(int userId, boolean disabled) throws Exception {
        Optional<User> userOptional = repository.findById(userId);
        if (!userOptional.isPresent()) {
            throw new Exception("用户不存在");
        }

        User user = userOptional.get();
        user.setDisabled(disabled);
        user.updata_date = new Date();
        
        return repository.save(user);
    }

    public User findUserById(int id) {
        return repository.findUserById(id);
    }

    /**
     * 判断是否为默认头像
     * @param avatarUrl 头像URL
     * @return 是否为默认头像
     */
    private boolean isDefaultAvatar(String avatarUrl) {
        return avatarUrl != null &&
                (avatarUrl.endsWith("/images/default-avatar.png") ||
                        avatarUrl.endsWith("default-avatar.png"));
    }

}